import hashlib

from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.hashers import check_password
from django.utils import timezone
from rest_framework.exceptions import APIException

UserModel = get_user_model()


class CustomValidationError(APIException):
    """
    继承并重写验证器返回的结果,避免暴露字段
    """

    def __init__(self, detail):
        self.detail = detail


class CustomBackend(ModelBackend):
    """
    Django原生认证方式
    """

    def authenticate(self, request, username_or_email=None, password=None, **kwargs):
        if username_or_email is None:
            username_or_email = kwargs.get(UserModel.USERNAME_FIELD)
        try:
            user = UserModel._default_manager.get_by_natural_key(username_or_email)
        except UserModel.DoesNotExist:
            UserModel().set_password(password)
        else:
            verify_password = check_password(password, user.password)
            if not verify_password:
                password = hashlib.md5(password.encode(encoding='UTF-8')).hexdigest()
                verify_password = check_password(password, user.password)
            if verify_password:

                if self.user_can_authenticate(user):
                    user.last_login = timezone.now()
                    user.save()
                    return user
                raise CustomValidationError("当前用户已被禁用，请联系管理员!")
